package com.atguigu.gmall.product.component;

import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.UUID;


/**
 * minio进行文件上传的组件
 */
@Configuration
@EnableConfigurationProperties(MinioProperties.class)//1.MinioProperties的属性绑定生效 2.MinioProperties放到容器中
public class MinioService {

    @Autowired
    MinioProperties minioProperties;

    @Autowired
    private MinioClient minioClient;

    /**
     * 容器中放一个操作minio的客户端
     * @return
     * @throws Exception
     */
    @Bean
    MinioClient minioClient() throws Exception {
        MinioClient minioClient = new MinioClient(
                minioProperties.getEndpoint(),
                minioProperties.getAccessKey(),
                minioProperties.getSecretKey());
        //判断默认用的桶是否存在
        if (!minioClient.bucketExists(minioProperties.getBucketName())){
            // 如果桶不存在,创建一个名为asiatrip的存储桶，用于存储照片的zip文件。
            minioClient.makeBucket(minioProperties.getBucketName());
        }
        return minioClient;
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    public String uploadFile(MultipartFile file) throws Exception{
        //String bucketName, String objectName, InputStream stream, PutObjectOptions options
        // 1.文件名
        String filename = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        //2.文件流
        InputStream stream = file.getInputStream();
        //3.上传的设置项
        PutObjectOptions options = new PutObjectOptions(stream.available(), -1);
        //设置上内容类型
        options.setContentType(file.getContentType());
        minioClient.putObject(minioProperties.getBucketName(), filename,stream,options);

        //4.返回可访问的路径
        String path = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" +filename;
        return path;
    }
}
